package com.sari.common.servlet;

/**
 * Created by 王世锋 on 2018/1/9.
 */
import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class DelegatingServletProxy extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private String targetServletBean;
    private HttpServlet proxy;

    @Override
    public void init() throws ServletException {
        this.targetServletBean = this.getInitParameter("targetServletBean");
        this.getServletBean();
    }

    @Override
    protected void service(HttpServletRequest request,
                           HttpServletResponse response) throws ServletException, IOException {
        proxy.service(request, response);
    }

    private void getServletBean() {
        ServletContext servletContext = this.getServletContext();
        WebApplicationContext wac = WebApplicationContextUtils
                .getRequiredWebApplicationContext(servletContext);
        this.proxy = (HttpServlet) wac.getBean(targetServletBean);
    }
}